import { defineStore } from 'pinia'
import { apiArcInfo, apiSeasonsSeriesList, apiSeasonsArchivesList } from '@renderer/api/bilibili'
import axios from 'axios'

interface State {
  default: number
}

export const useArtistStore = defineStore('artist', {
  state: (): State => ({
    default: 0
  }),
  getters: {},
  actions: {
    async getArtistInfo(mid: number): Promise<Record<string, any> | null> {
      const webid = await getWebid(mid)
      if (webid) {
        const { data, code } = await apiArcInfo({
          mid,
          w_webid: webid
        })
        if (code === 0) {
          return data
        }
      }
      return null
    },
    async getAlbums(mid: number): Promise<any[]> {
      const webid = await getWebid(mid)
      if (webid) {
        const params = {
          mid,
          w_webid: webid,
          page_num: 1,
          page_size: 20
        }
        const { data, code } = await apiSeasonsSeriesList(params)
        if (code === 0) {
          return data.items_lists.seasons_list
        }
      }
      return []
    },
    async getAlbumInfo(params: {
      mid: number
      seasonid: number
      pagenum: number
      pagesize: number
    }): Promise<any[]> {
      const { data, code } = await apiSeasonsArchivesList({
        mid: params.mid,
        season_id: params.seasonid,
        page_num: params.pagenum,
        page_size: params.pagesize
      })
      if (code === 0) {
        return data.archives
      }
      return []
    }
  }
})

const webidMap = new Map<number, string>()

async function getWebid(mid: number): Promise<string | null> {
  if (webidMap.has(mid)) {
    return webidMap.get(mid)!
  }
  const response = await axios.get('https://space.bilibili.com/' + mid)
  const reg = /<script id="__RENDER_DATA__" type="application\/json">(.*?)<\/script>/
  const match: RegExpExecArray | null = reg.exec(response.data)
  if (match) {
    const data = JSON.parse(decodeURIComponent(match[1]))
    webidMap.set(mid, data.access_id)
    return data.access_id
  }
  return null
}
